﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Messaging;
using System.Text;
using System.Threading.Tasks;

namespace BaiTu.QueueService.Providers.MessageFormatters
{
    public class ProtobufMessageFormater : IMessageFormatter
    {
        private Type type;
        public ProtobufMessageFormater(Type type)
        {
            this.type = type;
        }

        public bool CanRead(Message message)
        {
            return message.BodyStream != null && message.BodyStream.Length > 0;
        }

        public object Read(Message message)
        {
            return ProtoBuf.Meta.RuntimeTypeModel.Default.Deserialize(message.BodyStream, null, this.type);
        }

        [System.ThreadStatic]
        private static System.IO.MemoryStream mStream;

        public void Write(Message message, object obj)
        {
            if (mStream == null)
                mStream = new System.IO.MemoryStream();
            mStream.Position = 0;
            mStream.SetLength(0);
            ProtoBuf.Meta.RuntimeTypeModel.Default.Serialize(mStream, obj);
            message.BodyStream = mStream;
        }

        public object Clone()
        {
            return this;
        }
    }
}
